<template>
  <div class="table1">
    <el-form
      ref="ruleFormRef"
      :model="props.form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="商品分类：" prop="productCategoryId">
        <el-cascader
          v-model="cascaderVal"
          :options="cagetery"
          placeholder="请选择商品分类"
        />
      </el-form-item>
      <el-form-item label="商品名称：" prop="name">
        <el-input v-model="props.form.name" />
      </el-form-item>
      <el-form-item label="副标题：" prop="subTitle">
        <el-input v-model="props.form.subTitle" />
      </el-form-item>
      <el-form-item label="商品品牌：" prop="brandId">
        <el-select
          v-model="BrandVal"
          class="m-2"
          placeholder="请选择商品品牌"
          size="large"
        >
          <el-option
            v-for="(item, index) in productBrand"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        /></el-select>
      </el-form-item>
      <el-form-item label="商品介绍：">
        <el-input
          type="textarea"
          v-model="props.form.description"
          placeholder="请输入内容"
        />
      </el-form-item>
      <el-form-item label="商品货号：">
        <el-input v-model="props.form.productSn" />
      </el-form-item>
      <el-form-item label="商品售价：" prop="price">
        <el-input v-model="props.form.price" />
      </el-form-item>
      <el-form-item label="市场价：" prop="originalPrice">
        <el-input v-model="props.form.originalPrice" />
      </el-form-item>
      <el-form-item label="商品库存：">
        <el-input v-model="props.form.stock" />
      </el-form-item>
      <el-form-item label="计量单位：" prop="unit">
        <el-input v-model="props.form.unit" />
      </el-form-item>
      <el-form-item label="商品重量：" prop="weight">
        <el-input input-style="width:200px" v-model="props.form.weight" />
        <span style="margin-left: 50px">克</span>
      </el-form-item>
      <el-form-item label="排序：">
        <el-input v-model="props.form.sort" />
      </el-form-item>
      <el-form-item>
        <div class="btn">
          <el-button type="primary" @click="next(ruleFormRef)"
            >下一步，填写商品促销</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ApiCategoryWithChildren, ApiBrandWithChildren } from "../types/index";
import { FormInstance, FormRules } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { reactive, ref } from "vue";

// 路由
const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();

// 商品分类
const cagetery = ref<
  {
    value: number;
    label: string;
    children: { value: number; label: string }[];
  }[]
>([]);

// 请求商品分类
ApiCategoryWithChildren().then((res) => {
  if (res.code !== 200) return;
  cagetery.value = res.data.map((item) => ({
    value: item.id,
    label: item.name,
    children: item.children.map((citem) => ({
      value: citem.id,
      label: citem.name,
    })),
  }));
});

// 存级联选择器的选择值
const cascaderVal = ref<number[]>([]);

// 声明父组件床过来的值的类型
interface Props {
  form: IAddProductParams;
}

// 接受父组件的值
const props = withDefaults(defineProps<Props>(), {
  form: () => ({
    name: "",
  }),
});

// 接受父组件的方法
const emit = defineEmits(["changeStep"]);

// 商品品牌
// 存商品品牌
const productBrand = ref<IBrandData[]>();

// 存商品品牌select的值
const BrandVal = ref();

// 请求商品品牌
ApiBrandWithChildren().then((res) => {
  if (res.code !== 200) return;
  productBrand.value = res.data;
});

// 验证是否为正整数
const isInteger = (rule: any, value: any, callback: (i?: any) => any) => {
  if (!/(^[1-9]\d*$)/.test(value)) {
    callback(new Error("请输入正整数"));
  } else {
    callback();
  }
};

// 校验规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  subTitle: [{ required: true, message: "请输入商品副标题", trigger: "blur" }],
  productCategoryId: [
    { required: true, message: "请输入优惠卷名称", trigger: "blur" },
  ],
  brandId: [{ required: true, message: "请选择商品品牌", trigger: "blur" }],
  publishCount: [
    {
      required: true,
      trigger: "blur",
      validator: isInteger,
    },
  ],
  price: [
    {
      required: true,
      trigger: "blur",
      validator: isInteger,
    },
  ],
  originalPrice: [
    {
      required: true,
      trigger: "blur",
      validator: isInteger,
    },
  ],
  unit: [
    {
      required: true,
      trigger: "blur",
      validator: isInteger,
    },
  ],
  weight: [
    {
      required: true,
      trigger: "blur",
      validator: isInteger,
    },
  ],
  minPoint: [
    {
      required: true,
      validator: isInteger,
      trigger: "change",
    },
  ],
});

// 跳到下一页
const next = async (formEl: FormInstance | undefined) => {
  // emit("changeStep", 1);
  props.form.brandId = cascaderVal.value[cascaderVal.value.length - 1];
  props.form.productCategoryId = BrandVal.value;

  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      emit("changeStep", 1);
    } else {
    }
  });
};

// ElMessageBox.confirm("你确定添加此优惠卷吗", "提示", {
//         confirmButtonText: "确定",
//         cancelButtonText: "取消",
//       })
//         .then(() => {
//           if (!route.query.id) {
//             ApiAddCoupon(params.value).then((res) => {
//               if (res.code !== 200) return;
//               ElMessage.success("添加成功");
//               router.push("/sms/coupon");
//             });
//           } else {
//             ApiUpdateCoupon(
//               parseInt(route.query.id as string),
//               params.value
//             ).then((res) => {
//               if (res.code == 200) {
//                 ElMessage.success("修改成功");
//                 router.push("/sms/coupon");
//               }
//             });
//           }
//         })
//         .catch(() => {});

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// emit("changeStep", 1);
</script>

<style scoped lang="less">
.btn {
  margin: auto;
}
:deep(.el-form) {
  width: 70%;
  // background-color: #fac;
}
</style>
